import Taro, { useRouter } from '@tarojs/taro';
import { View, Button, Input, Text } from '@tarojs/components';
import { useEffect, useState } from 'react';
import { STATUS, courseInfo } from '../../configProvider';
import CourseCard from '../../components/Card/CourseCard';
import './index.scss';

const CheckStudentView: React.FC = () => {
  const router = useRouter();
  const { courseId, code } = router.params;
  const [course, setCourse] = useState<courseInfo>();
  const [verifyCode, setVerifyCode] = useState('');
  const [location, setLocation] = useState<any>();
  useEffect(() => {
    if (!course) {
      return;
    }
    if (course.method === 'GPS定位') {
      Taro.getLocation({
        type: "wgs84",
        success(res) {
          console.log(res)
          setLocation(res)
        }
      })
    }
  }, [course])
  useEffect(() => {
    Taro.cloud.callFunction({
      name: 'getCourse',
      data: {
        courseId: courseId,
      },
    }).then((res: any) => {
      console.log('queryCourse success', res.result.data);
      setCourse(res.result.data)
    }).catch((err) => {
      console.log('queryCourse fail', err);
    });
  }, [])

  const handleCheckIn = () => {

    if (!course) {
      console.log('course is null');
      return;
    }

    Taro.cloud.callFunction({
      name: 'updateCheck',
      data: {
        _id: courseId,
        code: code,
        verifyCode: verifyCode,
        location: location
      },
    }).then((res: any) => {
      console.log('updateCheck success', res);
      if (res.result.success) {
        Taro.showToast({
          title: '签到成功',
          icon: 'success',
          duration: 2000,
        });
        setTimeout(() => {
          Taro.navigateBack();
        }, 2000);
      } else {
        Taro.showModal({
          title: '签到失败',
          content: res.result.error
        })
      }
    }).catch((err) => {
      console.log('updateCheck fail', err);
    });
  };



  return (
    <View className='check-student-view'>
      {course && <CourseCard name={course.courseName} startTime={course.startTime}
        endTime={course.endTime} weekday={course.weekday} teacher={course.teacher}
        status={STATUS.STUDENT} startDate={course.startDate} endDate={course.endDate} />
      }
      <View className='common-title'>签到方式：{course?.method}</View>
      {
        course && course.method === '验证码' && <View className="common-card input-container">
          <Text>验证码</Text>
          <Input value={verifyCode} className="input" onInput={(e: any) => { setVerifyCode(e.target.value) }} />
        </View>
      }
      <Button onClick={handleCheckIn}>签到</Button>
    </View>
  );
};

export default CheckStudentView;
